package com.cl.taskScheduler;

import java.util.Date;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.Trigger;
import org.quartz.TriggerUtils;
import org.quartz.impl.StdSchedulerFactory;

/**
 * 指定任务多久间隔执行一次(一天可能会有多次的执行,第一次开始执行时间比较随机),频率较高,单位：秒
 * @author chenlu
 * @date 2018-3-27 上午11:22:28
 */
public class JobScheduler {
	/**
	 * 每天执行多次,频率高的
	 */
	public final static String INTERVAL_TRIGGER_TYPE = "INTERVAL";
	/**
	 * 每天只执行一次的
	 */
	public final static String DAY_TRIGGER_TYPE = "DAY";
	
    /****
     * @param jobName 任务名称，中文表示
     * @param jobClass 执行任务的类
     * @param firstTriggerTime 任务触发的时间
     * @param scanInterval 间隔多久再次触发(秒)/每天哪个时间点执行
     * @param triggerType 任务触发类型
     * @param scanKey 任务的key
     * @param scanDescTab 扫描任务的表(value)
     */
    @SuppressWarnings("rawtypes")
	public static boolean createJobScheduler(String jobName,Class jobClass,Date firstTriggerTime,int scanInterval,String triggerType,String scanKey,String scanDescTab)
    {       
         try{       
             Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();         
             scheduler.start();          
             scheduleJob(scheduler,jobName,jobClass,firstTriggerTime,scanInterval,triggerType,scanKey,scanDescTab);          
        }catch (SchedulerException ex){       
        	return false;
        }  
         return true;
    }      
    
    @SuppressWarnings("rawtypes")
	private static void scheduleJob(Scheduler scheduler, String jobName,Class jobClass,Date firstTriggerTime,int scanInterval,String triggerType,String scanKey,String scanDescTab) throws SchedulerException 
    {         
       JobDetail jobDetail = new JobDetail(jobName,Scheduler.DEFAULT_GROUP, jobClass);         
       jobDetail.getJobDataMap().put(scanKey, scanDescTab);   
       Trigger trigger = null;
       if(triggerType.equals(INTERVAL_TRIGGER_TYPE)){
    	    trigger = TriggerUtils.makeSecondlyTrigger(scanInterval); //多少秒触发一次        
       }else if(triggerType.equals(DAY_TRIGGER_TYPE)){
    	    trigger = TriggerUtils.makeDailyTrigger(scanInterval,0); //每天几点开始执行        
       }
       trigger.setName(jobName + "-Trigger");         
       trigger.setStartTime(firstTriggerTime);//第一次触发时间         
       scheduler.scheduleJob(jobDetail, trigger); 
    }
    
    public static boolean scheduleJobDel(String jobName) throws SchedulerException{      
    	Scheduler sched = StdSchedulerFactory.getDefaultScheduler();
    	return sched.deleteJob(jobName, Scheduler.DEFAULT_GROUP);
    }
}
